package ThreadSafety;

public class Locked {
    /**死锁
     * 线程t1尝试获得到锁locked1和locked2,线程t2尝试获得锁locked2和locked1
     * 线程t1在获取锁locked2的时候等待线程t2释放锁locked2,同时线程2在获取锁locked1的时候等待线程t1释放锁locked1
     * 因为都释放不了所以就会出现锁竞争的情况,也就是死锁
     * 线程1在拿到锁locked1之后,在尝试获取锁locked2,锁locked1还是保持的,不会因为获取锁locked2而释放
     */
    public static void main(String[] args) {
        //解决死锁的方法:给锁编号,先取小的锁,后拿大的锁(避免循环等待)
        Object locked1 = new Object();
        Object locked2 = new Object();
        Thread t1 = new Thread(()->{
            synchronized (locked2) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                synchronized (locked1) {
                    System.out.println("得到了两把锁:locked1 和 locked2");
                }
            }
        });
        Thread t2 = new Thread(()->{
            synchronized (locked1) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                synchronized (locked2) {
                    System.out.println("得到了两把锁:locked2 和 locked1");
                }
            }
        });
        t1.start();
        t2.start();
    }
}
